home *** CD-ROM | disk | FTP | other *** search
/ Risc World 5 / Risc World 5.iso / SOFTWARE / Issue5 / PD / DIRSYNC / LegalStuff / gnudiff / diff.c < prev    next >
C/C++ Source or Header  |  2004-12-19  |  43KB  |  1,582 lines

  1. /* diff - compare files line by line
  2.  
  3.    Copyright (C) 1988, 1989, 1992, 1993, 1994, 1996, 1998, 2001, 2002
  4.    Free Software Foundation, Inc.
  5.  
  6.    This file is part of GNU DIFF.
  7.  
  8.    GNU DIFF is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    GNU DIFF is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  16.    See the GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with GNU DIFF; see the file COPYING.
  20.    If not, write to the Free Software Foundation,
  21.    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  22.  
  23. #define GDIFF_MAIN
  24. /* Hack for Norcroft C */
  25. #include <config.h>
  26. #include <regex.h>
  27. /* End hack */
  28. #include "diff.h"
  29. #include <c-stack.h>
  30. #ifdef __riscos
  31. #include "basename.h"
  32. #else
  33. #include <dirname.h>
  34. #endif
  35. #include <error.h>
  36. #include <exclude.h>
  37. #include <exitfail.h>
  38. #include <fnmatch.h>
  39. #include <freesoft.h>
  40. #include <getopt.h>
  41. #include <hard-locale.h>
  42. #include <prepargs.h>
  43. #include <quotesys.h>
  44. #ifndef __riscos
  45. #include <setmode.h>
  46. #endif
  47. #include <xalloc.h>
  48. #include <posixver.h>
  49.  
  50. #ifdef __riscos
  51. # include "alloca.h"
  52. # include "ro_uname.h"
  53. # define RO_EXTRA_OPTS "/::&|:"
  54. #else
  55. # define RO_EXTRA_OPTS
  56. #endif
  57.  
  58. static char const authorship_msgid[] =
  59.   N_("Written by Paul Eggert, Mike Haertel, David Hayes,\n\
  60. Richard Stallman, and Len Tower.");
  61.  
  62. static char const copyright_string[] =
  63.   "Copyright (C) 2002 Free Software Foundation, Inc.";
  64.  
  65. #ifndef GUTTER_WIDTH_MINIMUM
  66. # define GUTTER_WIDTH_MINIMUM 3
  67. #endif
  68.  
  69. struct regexp_list
  70. {
  71.   char *regexps;    /* chars representing disjunction of the regexps */
  72.   size_t len;        /* chars used in `regexps' */
  73.   size_t size;        /* size malloc'ed for `regexps'; 0 if not malloc'ed */
  74.   bool multiple_regexps;/* Does `regexps' represent a disjunction?  */
  75.   struct re_pattern_buffer *buf;
  76. };
  77.  
  78. #ifdef __riscos
  79. static int compare_files (struct comparison const *, char const *, char const *, char const *, char const *);
  80. static int compare_files_nofilter (struct comparison const *, char const *, char const *);
  81. #define FILTER , filter_left, filter_right
  82. #else
  83. static int compare_files (struct comparison const *, char const *, char const *);
  84. #define FILTER
  85. #endif
  86. static void add_regexp (struct regexp_list *, char const *);
  87. static void summarize_regexp_list (struct regexp_list *);
  88. static void specify_style (enum output_style);
  89. static void specify_value (char const **, char const *, char const *);
  90. static void try_help (char const *, char const *) __attribute__((noreturn));
  91. static void check_stdout (void);
  92. static void usage (void);
  93.  
  94. /* If comparing directories, compare their common subdirectories
  95.    recursively.  */
  96. static bool recursive;
  97.  
  98. /* In context diffs, show previous lines that match these regexps.  */
  99. static struct regexp_list function_regexp_list;
  100.  
  101. /* Ignore changes affecting only lines that match these regexps.  */
  102. static struct regexp_list ignore_regexp_list;
  103.  
  104. #if HAVE_SETMODE_DOS
  105. /* Use binary I/O when reading and writing data (--binary).
  106.    On POSIX hosts, this has no effect.  */
  107. static bool binary;
  108. #endif
  109.  
  110. /* When comparing directories, if a file appears only in one
  111.    directory, treat it as present but empty in the other (-N).
  112.    Then `patch' would create the file with appropriate contents.  */
  113. static bool new_file;
  114.  
  115. /* When comparing directories, if a file appears only in the second
  116.    directory of the two, treat it as present but empty in the other
  117.    (--unidirectional-new-file).
  118.    Then `patch' would create the file with appropriate contents.  */
  119. static bool unidirectional_new_file;
  120.  
  121. /* Report files compared that are the same (-s).
  122.    Normally nothing is output when that happens.  */
  123. static bool report_identical_files;
  124.  
  125.  
  126. /* Return a string containing the command options with which diff was invoked.
  127.    Spaces appear between what were separate ARGV-elements.
  128.    There is a space at the beginning but none at the end.
  129.    If there were no options, the result is an empty string.
  130.  
  131.    Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
  132.    the length of that vector.  */
  133.  
  134. static char *
  135. option_list (char **optionvec, int count)
  136. {
  137.   int i;
  138.   size_t size = 1;
  139.   char *result;
  140.   char *p;
  141.  
  142.   for (i = 0; i < count; i++)
  143.     size += 1 + quote_system_arg ((char *) 0, optionvec[i]);
  144.  
  145.   p = result = xmalloc (size);
  146.  
  147.   for (i = 0; i < count; i++)
  148.     {
  149.       *p++ = ' ';
  150.       p += quote_system_arg (p, optionvec[i]);
  151.     }
  152.  
  153.   *p = 0;
  154.   return result;
  155. }
  156.  
  157.  
  158. /* Return an option value suitable for add_exclude.  */
  159.  
  160. static int
  161. exclude_options (void)
  162. {
  163.   return EXCLUDE_WILDCARDS | (ignore_file_name_case ? FNM_CASEFOLD : 0);
  164. }
  165.  
  166. static char const shortopts[] =
  167. "0123456789abBcC:dD:eEfF:hHiI:lL:nNpPqrsS:tTuU:vwW:x:X:y" RO_EXTRA_OPTS;
  168.  
  169. /* Values for long options that do not have single-letter equivalents.  */
  170. enum
  171. {
  172.   BINARY_OPTION = CHAR_MAX + 1,
  173.   FROM_FILE_OPTION,
  174.   HELP_OPTION,
  175.   HORIZON_LINES_OPTION,
  176.   IGNORE_FILE_NAME_CASE_OPTION,
  177.   INHIBIT_HUNK_MERGE_OPTION,
  178.   LEFT_COLUMN_OPTION,
  179.   LINE_FORMAT_OPTION,
  180.   NO_IGNORE_FILE_NAME_CASE_OPTION,
  181.   NORMAL_OPTION,
  182.   SDIFF_MERGE_ASSIST_OPTION,
  183.   STRIP_TRAILING_CR_OPTION,
  184.   SUPPRESS_COMMON_LINES_OPTION,
  185.   TO_FILE_OPTION,
  186.  
  187.   /* These options must be in sequence.  */
  188.   UNCHANGED_LINE_FORMAT_OPTION,
  189.   OLD_LINE_FORMAT_OPTION,
  190.   NEW_LINE_FORMAT_OPTION,
  191.  
  192.   /* These options must be in sequence.  */
  193.   UNCHANGED_GROUP_FORMAT_OPTION,
  194.   OLD_GROUP_FORMAT_OPTION,
  195.   NEW_GROUP_FORMAT_OPTION,
  196.   CHANGED_GROUP_FORMAT_OPTION
  197. };
  198.  
  199. static char const group_format_option[][sizeof "--unchanged-group-format"] =
  200.   {
  201.     "--unchanged-group-format",
  202.     "--old-group-format",
  203.     "--new-group-format",
  204.     "--changed-group-format"
  205.   };
  206.  
  207. static char const line_format_option[][sizeof "--unchanged-line-format"] =
  208.   {
  209.     "--unchanged-line-format",
  210.     "--old-line-format",
  211.     "--new-line-format"
  212.   };
  213.  
  214. static struct option const longopts[] =
  215. {
  216.   {"binary", 0, 0, BINARY_OPTION},
  217.   {"brief", 0, 0, 'q'},
  218.   {"changed-group-format", 1, 0, CHANGED_GROUP_FORMAT_OPTION},
  219.   {"context", 2, 0, 'C'},
  220.   {"ed", 0, 0, 'e'},
  221.   {"exclude", 1, 0, 'x'},
  222.   {"exclude-from", 1, 0, 'X'},
  223.   {"expand-tabs", 0, 0, 't'},
  224.   {"forward-ed", 0, 0, 'f'},
  225.   {"from-file", 1, 0, FROM_FILE_OPTION},
  226.   {"help", 0, 0, HELP_OPTION},
  227.   {"horizon-lines", 1, 0, HORIZON_LINES_OPTION},
  228.   {"ifdef", 1, 0, 'D'},
  229.   {"ignore-all-space", 0, 0, 'w'},
  230.   {"ignore-blank-lines", 0, 0, 'B'},
  231.   {"ignore-case", 0, 0, 'i'},
  232.   {"ignore-file-name-case", 0, 0, IGNORE_FILE_NAME_CASE_OPTION},
  233.   {"ignore-matching-lines", 1, 0, 'I'},
  234.   {"ignore-space-change", 0, 0, 'b'},
  235.   {"ignore-tab-expansion", 0, 0, 'E'},
  236.   {"inhibit-hunk-merge", 0, 0, INHIBIT_HUNK_MERGE_OPTION},
  237.   {"initial-tab", 0, 0, 'T'},
  238.   {"label", 1, 0, 'L'},
  239.   {"left-column", 0, 0, LEFT_COLUMN_OPTION},
  240.   {"line-format", 1, 0, LINE_FORMAT_OPTION},
  241.   {"minimal", 0, 0, 'd'},
  242.   {"new-file", 0, 0, 'N'},
  243.   {"new-group-format", 1, 0, NEW_GROUP_FORMAT_OPTION},
  244.   {"new-line-format", 1, 0, NEW_LINE_FORMAT_OPTION},
  245.   {"no-ignore-file-name-case", 0, 0, NO_IGNORE_FILE_NAME_CASE_OPTION},
  246.   {"normal", 0, 0, NORMAL_OPTION},
  247.   {"old-group-format", 1, 0, OLD_GROUP_FORMAT_OPTION},
  248.   {"old-line-format", 1, 0, OLD_LINE_FORMAT_OPTION},
  249.   {"paginate", 0, 0, 'l'},
  250.   {"rcs", 0, 0, 'n'},
  251.   {"recursive", 0, 0, 'r'},
  252.   {"report-identical-files", 0, 0, 's'},
  253.   {"sdiff-merge-assist", 0, 0, SDIFF_MERGE_ASSIST_OPTION},
  254.   {"show-c-function", 0, 0, 'p'},
  255.   {"show-function-line", 1, 0, 'F'},
  256.   {"side-by-side", 0, 0, 'y'},
  257.   {"speed-large-files", 0, 0, 'H'},
  258.   {"starting-file", 1, 0, 'S'},
  259.   {"strip-trailing-cr", 0, 0, STRIP_TRAILING_CR_OPTION},
  260.   {"suppress-common-lines", 0, 0, SUPPRESS_COMMON_LINES_OPTION},
  261.   {"text", 0, 0, 'a'},
  262.   {"to-file", 1, 0, TO_FILE_OPTION},
  263.   {"unchanged-group-format", 1, 0, UNCHANGED_GROUP_FORMAT_OPTION},
  264.   {"unchanged-line-format", 1, 0, UNCHANGED_LINE_FORMAT_OPTION},
  265.   {"unidirectional-new-file", 0, 0, 'P'},
  266.   {"unified", 2, 0, 'U'},
  267.   {"version", 0, 0, 'v'},
  268.   {"width", 1, 0, 'W'},
  269. #ifdef __riscos
  270.   {"unix-filenames", 2, 0, '/'},
  271.   {"append-filetypes", 0, 0, '&'},
  272.   {"filter", 1, 0, '|'},
  273. #endif
  274.   {0, 0, 0, 0}
  275. };
  276.  
  277. int
  278. main (int argc, char **argv)
  279. {
  280.   int exit_status = EXIT_SUCCESS;
  281.   int c;
  282.   int i;
  283.   int prev = -1;
  284.   lin ocontext = -1;
  285.   bool explicit_context = 0;
  286.   int width = 0;
  287.   bool show_c_function = 0;
  288.   char const *from_file = 0;
  289.   char const *to_file = 0;
  290.   uintmax_t numval;
  291.   char *numend;
  292. #ifdef __riscos
  293.   const char *filter_left = 0, *filter_right = 0;
  294. #endif
  295.  
  296.   /* Do our initializations.  */
  297.   exit_failure = 2;
  298.   initialize_main (&argc, &argv);
  299.   program_name = argv[0];
  300.   setlocale (LC_ALL, "");
  301.   bindtextdomain (PACKAGE, LOCALEDIR);
  302.   textdomain (PACKAGE);
  303.   c_stack_action (c_stack_die);
  304.   function_regexp_list.buf = &function_regexp;
  305.   ignore_regexp_list.buf = &ignore_regexp;
  306.   re_set_syntax (RE_SYNTAX_GREP | RE_NO_POSIX_BACKTRACKING);
  307.   excluded = new_exclude ();
  308.  
  309.   /* Decode the options.  */
  310.  
  311. #ifdef __riscos
  312.   CHECK_TAB_EXPAND (expand_tabs);
  313. #endif
  314.  
  315.   while ((c = getopt_long (argc, argv, shortopts, longopts, 0)) != -1)
  316.     {
  317.       switch (c)
  318.     {
  319.     case 0:
  320.       break;
  321.  
  322.     case '0':
  323.     case '1':
  324.     case '2':
  325.     case '3':
  326.     case '4':
  327.     case '5':
  328.     case '6':
  329.     case '7':
  330.     case '8':
  331.     case '9':
  332.       if (! ISDIGIT (prev))
  333.         ocontext = c - '0';
  334.       else if (LIN_MAX / 10 < ocontext
  335.            || ((ocontext = 10 * ocontext + c - '0') < 0))
  336.         ocontext = LIN_MAX;
  337.       break;
  338.  
  339.     case 'a':
  340.       text = 1;
  341.       break;
  342.  
  343.     case 'b':
  344.       if (ignore_white_space < IGNORE_SPACE_CHANGE)
  345.         ignore_white_space = IGNORE_SPACE_CHANGE;
  346.       break;
  347.  
  348.     case 'B':
  349.       ignore_blank_lines = 1;
  350.       break;
  351.  
  352.     case 'C':        /* +context[=lines] */
  353.     case 'U':        /* +unified[=lines] */
  354.       {
  355.         if (optarg)
  356.           {
  357.         numval = strtoumax (optarg, &numend, 10);
  358.         if (*numend)
  359.           try_help ("invalid context length `%s'", optarg);
  360.         if (LIN_MAX < numval)
  361.           numval = LIN_MAX;
  362.           }
  363.         else
  364.           numval = 3;
  365.  
  366.         specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
  367.         if (context < numval)
  368.           context = numval;
  369.         explicit_context = 1;
  370.       }
  371.       break;
  372.  
  373.     case 'c':
  374.       specify_style (OUTPUT_CONTEXT);
  375.       if (context < 3)
  376.         context = 3;
  377.       break;
  378.  
  379.     case 'd':
  380.       minimal = 1;
  381.       break;
  382.  
  383.     case 'D':
  384.       specify_style (OUTPUT_IFDEF);
  385.       {
  386.         static char const C_ifdef_group_formats[] =
  387.           "%%=%c#ifndef %s\n%%<#endif /* ! %s */\n%c#ifdef %s\n%%>#endif /* %s */\n%c#ifndef %s\n%%<#else /* %s */\n%%>#endif /* %s */\n";
  388.         char *b = xmalloc (sizeof C_ifdef_group_formats
  389.                    + 7 * strlen (optarg) - 14 /* 7*"%s" */
  390.                    - 8 /* 5*"%%" + 3*"%c" */);
  391.         sprintf (b, C_ifdef_group_formats,
  392.              0,
  393.              optarg, optarg, 0,
  394.              optarg, optarg, 0,
  395.              optarg, optarg, optarg);
  396.         for (i = 0; i < sizeof group_format / sizeof *group_format; i++)
  397.           {
  398.         specify_value (&group_format[i], b, "-D");
  399.         b += strlen (b) + 1;
  400.           }
  401.       }
  402.       break;
  403.  
  404.     case 'e':
  405.       specify_style (OUTPUT_ED);
  406.       break;
  407.  
  408.     case 'E':
  409.       if (ignore_white_space < IGNORE_TAB_EXPANSION)
  410.         ignore_white_space = IGNORE_TAB_EXPANSION;
  411.       break;
  412.  
  413.     case 'f':
  414.       specify_style (OUTPUT_FORWARD_ED);
  415.       break;
  416.  
  417.     case 'F':
  418.       add_regexp (&function_regexp_list, optarg);
  419.       break;
  420.  
  421.     case 'h':
  422.       /* Split the files into chunks for faster processing.
  423.          Usually does not change the result.
  424.  
  425.          This currently has no effect.  */
  426.       break;
  427.  
  428.     case 'H':
  429.       speed_large_files = 1;
  430.       break;
  431.  
  432.     case 'i':
  433.       ignore_case = 1;
  434.       break;
  435.  
  436.     case 'I':
  437.       add_regexp (&ignore_regexp_list, optarg);
  438.       break;
  439.  
  440.     case 'l':
  441.       if (!pr_program[0])
  442.         try_help ("pagination not supported on this host", 0);
  443.       paginate = 1;
  444. #ifdef SIGCHLD
  445.       /* Pagination requires forking and waiting, and
  446.          System V fork+wait does not work if SIGCHLD is ignored.  */
  447.       signal (SIGCHLD, SIG_DFL);
  448. #endif
  449.       break;
  450.  
  451.     case 'L':
  452.       if (!file_label[0])
  453.         file_label[0] = optarg;
  454.       else if (!file_label[1])
  455.         file_label[1] = optarg;
  456.       else
  457.         fatal ("too many file label options");
  458.       break;
  459.  
  460.     case 'n':
  461.       specify_style (OUTPUT_RCS);
  462.       break;
  463.  
  464.     case 'N':
  465.       new_file = 1;
  466.       break;
  467.  
  468.     case 'p':
  469.       show_c_function = 1;
  470.       add_regexp (&function_regexp_list, "^[[:alpha:]$_]");
  471.       break;
  472.  
  473.     case 'P':
  474.       unidirectional_new_file = 1;
  475.       break;
  476.  
  477.     case 'q':
  478.       brief = 1;
  479.       break;
  480.  
  481.     case 'r':
  482.       recursive = 1;
  483.       break;
  484.  
  485.     case 's':
  486.       report_identical_files = 1;
  487.       break;
  488.  
  489.     case 'S':
  490.       specify_value (&starting_file, optarg, "-S");
  491.       break;
  492.  
  493.     case 't':
  494.       expand_tabs = 1;
  495.       break;
  496.  
  497.     case 'T':
  498.       initial_tab = 1;
  499.       break;
  500.  
  501.     case 'u':
  502.       specify_style (OUTPUT_UNIFIED);
  503.       if (context < 3)
  504.         context = 3;
  505.       break;
  506.  
  507.     case 'v':
  508.       printf ("diff %s\n%s\n\n%s\n\n%s\n",
  509.           version_string, copyright_string,
  510.           _(free_software_msgid), _(authorship_msgid));
  511.       check_stdout ();
  512.       return EXIT_SUCCESS;
  513.  
  514.     case 'w':
  515.       ignore_white_space = IGNORE_ALL_SPACE;
  516.       break;
  517.  
  518.     case 'x':
  519.       add_exclude (excluded, optarg, exclude_options ());
  520.       break;
  521.  
  522.     case 'X':
  523.       if (add_exclude_file (add_exclude, excluded, optarg,
  524.                 exclude_options (), '\n'))
  525.         pfatal_with_name (optarg);
  526.       break;
  527.  
  528.     case 'y':
  529.       specify_style (OUTPUT_SDIFF);
  530.       break;
  531.  
  532.     case 'W':
  533.       numval = strtoumax (optarg, &numend, 10);
  534.       if (! (0 < numval && numval <= INT_MAX) || *numend)
  535.         try_help ("invalid width `%s'", optarg);
  536.       if (width != numval)
  537.         {
  538.           if (width)
  539.         fatal ("conflicting width options");
  540.           width = numval;
  541.         }
  542.       break;
  543.  
  544.     case BINARY_OPTION:
  545. #if HAVE_SETMODE_DOS
  546.       binary = 1;
  547.       set_binary_mode (STDOUT_FILENO, 1);
  548. #endif
  549.       break;
  550.  
  551.     case FROM_FILE_OPTION:
  552.       specify_value (&from_file, optarg, "--from-file");
  553.       break;
  554.  
  555.     case HELP_OPTION:
  556.       usage ();
  557.       check_stdout ();
  558.       return EXIT_SUCCESS;
  559.  
  560.     case HORIZON_LINES_OPTION:
  561.       numval = strtoumax (optarg, &numend, 10);
  562.       if (*numend)
  563.         try_help ("invalid horizon length `%s'", optarg);
  564.       horizon_lines = MAX (horizon_lines, MIN (numval, LIN_MAX));
  565.       break;
  566.  
  567.     case IGNORE_FILE_NAME_CASE_OPTION:
  568.       ignore_file_name_case = 1;
  569.       break;
  570.  
  571.     case INHIBIT_HUNK_MERGE_OPTION:
  572.       /* This option is obsolete, but accept it for backward
  573.              compatibility.  */
  574.       break;
  575.  
  576.     case LEFT_COLUMN_OPTION:
  577.       left_column = 1;
  578.       break;
  579.  
  580.     case LINE_FORMAT_OPTION:
  581.       specify_style (OUTPUT_IFDEF);
  582.       for (i = 0; i < sizeof line_format / sizeof *line_format; i++)
  583.         specify_value (&line_format[i], optarg, "--line-format");
  584.       break;
  585.  
  586.     case NO_IGNORE_FILE_NAME_CASE_OPTION:
  587.       ignore_file_name_case = 0;
  588.       break;
  589.  
  590.     case NORMAL_OPTION:
  591.       specify_style (OUTPUT_NORMAL);
  592.       break;
  593.  
  594.     case SDIFF_MERGE_ASSIST_OPTION:
  595.       specify_style (OUTPUT_SDIFF);
  596.       sdiff_merge_assist = 1;
  597.       break;
  598.  
  599.     case STRIP_TRAILING_CR_OPTION:
  600.       strip_trailing_cr = 1;
  601.       break;
  602.  
  603.     case SUPPRESS_COMMON_LINES_OPTION:
  604.       suppress_common_lines = 1;
  605.       break;
  606.  
  607.     case TO_FILE_OPTION:
  608.       specify_value (&to_file, optarg, "--to-file");
  609.       break;
  610.  
  611.     case UNCHANGED_LINE_FORMAT_OPTION:
  612.     case OLD_LINE_FORMAT_OPTION:
  613.     case NEW_LINE_FORMAT_OPTION:
  614.       specify_style (OUTPUT_IFDEF);
  615.       c -= UNCHANGED_LINE_FORMAT_OPTION;
  616.       specify_value (&line_format[c], optarg, line_format_option[c]);
  617.       break;
  618.  
  619.     case UNCHANGED_GROUP_FORMAT_OPTION:
  620.     case OLD_GROUP_FORMAT_OPTION:
  621.     case NEW_GROUP_FORMAT_OPTION:
  622.     case CHANGED_GROUP_FORMAT_OPTION:
  623.       specify_style (OUTPUT_IFDEF);
  624.       c -= UNCHANGED_GROUP_FORMAT_OPTION;
  625.       specify_value (&group_format[c], optarg, group_format_option[c]);
  626.       break;
  627.  
  628. #ifdef __riscos
  629.     case '/':
  630.       extensions_string = optarg ? optarg : "";
  631.       break;
  632.  
  633.     case '&':
  634.       append_filetypes = 1;
  635.       break;
  636.  
  637.     case '|':
  638.       switch (*optarg)
  639.         {
  640.           case '<': filter_left = optarg + 1; break;
  641.           case '>': filter_right = optarg + 1; break;
  642.           default: filter_left = filter_right = optarg;
  643.         }
  644.       break;
  645. #endif
  646.  
  647.     default:
  648.       try_help (0, 0);
  649.     }
  650.       prev = c;
  651.     }
  652.  
  653.   if (output_style == OUTPUT_UNSPECIFIED)
  654.     {
  655.       if (show_c_function)
  656.     {
  657.       specify_style (OUTPUT_CONTEXT);
  658.       if (ocontext < 0)
  659.         context = 3;
  660.     }
  661.       else
  662.     specify_style (OUTPUT_NORMAL);
  663.     }
  664.  
  665.   if (output_style != OUTPUT_CONTEXT || hard_locale (LC_TIME))
  666.     time_format = "%Y-%m-%d %H:%M:%S.%N %z";
  667.   else
  668.     {
  669.       /* See POSIX 1003.1-2001 for this format.  */
  670.       time_format = "%a %b %e %T %Y";
  671.     }
  672.  
  673.   if (0 <= ocontext)
  674.     {
  675.       bool modern_usage = 200112 <= posix2_version ();
  676.  
  677.       if ((output_style == OUTPUT_CONTEXT
  678.        || output_style == OUTPUT_UNIFIED)
  679.       && (context < ocontext
  680.           || (ocontext < context && ! explicit_context)))
  681.     {
  682.       if (modern_usage)
  683.         {
  684.           error (0, 0,
  685.              _("`-%ld' option is obsolete; use `-%c %ld'"),
  686.              (long) ocontext,
  687.              output_style == OUTPUT_CONTEXT ? 'C' : 'U',
  688.              (long) ocontext);
  689.           try_help (0, 0);
  690.         }
  691.       context = ocontext;
  692.     }
  693.       else
  694.     {
  695.       if (modern_usage)
  696.         {
  697.           error (0, 0, _("`-%ld' option is obsolete; omit it"),
  698.              (long) ocontext);
  699.           try_help (0, 0);
  700.         }
  701.     }
  702.     }
  703.  
  704. #ifdef __riscos
  705.   if (paginate)
  706.     fatal("sorry, --paginate not implemented");
  707.  
  708.   if (filter_left)
  709.     {
  710.       while (isspace (*filter_left))
  711.     filter_left++;
  712.       if (!*filter_left)
  713.     filter_left = 0;
  714.     }
  715.  
  716.   if (filter_right)
  717.     {
  718.       while (isspace (*filter_right))
  719.     filter_right++;
  720.       if (!*filter_right)
  721.     filter_right = 0;
  722.     }
  723. #endif
  724.  
  725.   {
  726.     /*
  727.      *    We maximize first the half line width, and then the gutter width,
  728.      *    according to the following constraints:
  729.      *    1.  Two half lines plus a gutter must fit in a line.
  730.      *    2.  If the half line width is nonzero:
  731.      *        a.  The gutter width is at least GUTTER_WIDTH_MINIMUM.
  732.      *        b.  If tabs are not expanded to spaces,
  733.      *        a half line plus a gutter is an integral number of tabs,
  734.      *        so that tabs in the right column line up.
  735.      */
  736.     unsigned int t = expand_tabs ? 1 : TAB_WIDTH;
  737.     int w = width ? width : 130;
  738.     int off = (w + t + GUTTER_WIDTH_MINIMUM) / (2 * t)  *  t;
  739.     sdiff_half_width = MAX (0, MIN (off - GUTTER_WIDTH_MINIMUM, w - off)),
  740.     sdiff_column2_offset = sdiff_half_width ? off : w;
  741.   }
  742.  
  743.   /* Make the horizon at least as large as the context, so that
  744.      shift_boundaries has more freedom to shift the first and last hunks.  */
  745.   if (horizon_lines < context)
  746.     horizon_lines = context;
  747.  
  748.   summarize_regexp_list (&function_regexp_list);
  749.   summarize_regexp_list (&ignore_regexp_list);
  750.  
  751.   if (output_style == OUTPUT_IFDEF)
  752.     {
  753.       for (i = 0; i < sizeof line_format / sizeof *line_format; i++)
  754.     if (!line_format[i])
  755.       line_format[i] = "%l\n";
  756.       if (!group_format[OLD])
  757.     group_format[OLD]
  758.       = group_format[CHANGED] ? group_format[CHANGED] : "%<";
  759.       if (!group_format[NEW])
  760.     group_format[NEW]
  761.       = group_format[CHANGED] ? group_format[CHANGED] : "%>";
  762.       if (!group_format[UNCHANGED])
  763.     group_format[UNCHANGED] = "%=";
  764.       if (!group_format[CHANGED])
  765.     group_format[CHANGED] = concat (group_format[OLD],
  766.                     group_format[NEW], "");
  767.     }
  768.  
  769.   no_diff_means_no_output =
  770.     (output_style == OUTPUT_IFDEF ?
  771.       (!*group_format[UNCHANGED]
  772.        || (strcmp (group_format[UNCHANGED], "%=") == 0
  773.        && !*line_format[UNCHANGED]))
  774.      : (output_style != OUTPUT_SDIFF) | suppress_common_lines);
  775.  
  776.   files_can_be_treated_as_binary =
  777.     (brief
  778.      & ~ (ignore_blank_lines | ignore_case | strip_trailing_cr
  779.       | (ignore_regexp_list.regexps || ignore_white_space)));
  780.  
  781.   switch_string = option_list (argv + 1, optind - 1);
  782.  
  783.   if (from_file)
  784.     {
  785.       if (to_file)
  786.     fatal ("--from-file and --to-file both specified");
  787.       else
  788.     for (; optind < argc; optind++)
  789.       {
  790.         int status = compare_files ((struct comparison *) 0,
  791.                     from_file, argv[optind] FILTER);
  792.         if (exit_status < status)
  793.           exit_status = status;
  794.       }
  795.     }
  796.   else
  797.     {
  798.       if (to_file)
  799.     for (; optind < argc; optind++)
  800.       {
  801.         int status = compare_files ((struct comparison *) 0,
  802.                     argv[optind], to_file FILTER);
  803.         if (exit_status < status)
  804.           exit_status = status;
  805.       }
  806.       else
  807.     {
  808.       if (argc - optind != 2)
  809.         {
  810.           if (argc - optind < 2)
  811.         try_help ("missing operand after `%s'", argv[argc - 1]);
  812.           else
  813.         try_help ("extra operand `%s'", argv[optind + 2]);
  814.         }
  815.  
  816.       exit_status = compare_files ((struct comparison *) 0,
  817.                        argv[optind], argv[optind + 1] FILTER);
  818.     }
  819.     }
  820.  
  821.   /* Print any messages that were saved up for last.  */
  822. #ifndef __riscos
  823.   print_message_queue ();
  824. #endif
  825.  
  826.   check_stdout ();
  827.   exit (exit_status);
  828.   return exit_status;
  829. }
  830.  
  831. /* Append to REGLIST the regexp PATTERN.  */
  832.  
  833. static void
  834. add_regexp (struct regexp_list *reglist, char const *pattern)
  835. {
  836.   size_t patlen = strlen (pattern);
  837.   char const *m = re_compile_pattern (pattern, patlen, reglist->buf);
  838.  
  839.   if (m != 0)
  840.     error (0, 0, "%s: %s", pattern, m);
  841.   else
  842.     {
  843.       char *regexps = reglist->regexps;
  844.       size_t len = reglist->len;
  845.       bool multiple_regexps = reglist->multiple_regexps = regexps != 0;
  846.       size_t newlen = reglist->len = len + 2 * multiple_regexps + patlen;
  847.       size_t size = reglist->size;
  848.  
  849.       if (size <= newlen)
  850.     {
  851.       if (!size)
  852.         size = 1;
  853.  
  854.       do size *= 2;
  855.       while (size <= newlen);
  856.  
  857.       reglist->size = size;
  858.       reglist->regexps = regexps = xrealloc (regexps, size);
  859.     }
  860.       if (multiple_regexps)
  861.     {
  862.       regexps[len++] = '\\';
  863.       regexps[len++] = '|';
  864.     }
  865.       memcpy (regexps + len, pattern, patlen + 1);
  866.     }
  867. }
  868.  
  869. /* Ensure that REGLIST represents the disjunction of its regexps.
  870.    This is done here, rather than earlier, to avoid O(N^2) behavior.  */
  871.  
  872. static void
  873. summarize_regexp_list (struct regexp_list *reglist)
  874. {
  875.   if (reglist->regexps)
  876.     {
  877.       /* At least one regexp was specified.  Allocate a fastmap for it.  */
  878.       reglist->buf->fastmap = xmalloc (1 << CHAR_BIT);
  879.       if (reglist->multiple_regexps)
  880.     {
  881.       /* Compile the disjunction of the regexps.
  882.          (If just one regexp was specified, it is already compiled.)  */
  883.       char const *m = re_compile_pattern (reglist->regexps, reglist->len,
  884.                           reglist->buf);
  885.       if (m != 0)
  886.         error (EXIT_TROUBLE, 0, "%s: %s", reglist->regexps, m);
  887.     }
  888.     }
  889. }
  890.  
  891. static void
  892. try_help (char const *reason_msgid, char const *operand)
  893. {
  894.   if (reason_msgid)
  895.     error (0, 0, _(reason_msgid), operand);
  896.   error (EXIT_TROUBLE, 0, _("Try `%s --help' for more information."),
  897.      program_name);
  898.   abort ();
  899. }
  900.  
  901. static void
  902. check_stdout (void)
  903. {
  904.   if (ferror (stdout))
  905.     fatal ("write failed");
  906.   else if (fclose (stdout) != 0)
  907.     pfatal_with_name (_("standard output"));
  908. }
  909.  
  910. static char const * const option_help_msgid[] = {
  911.   N_("Compare files line by line."),
  912.   "",
  913.   N_("-i  --ignore-case  Ignore case differences in file contents."),
  914.   N_("--ignore-file-name-case  Ignore case when comparing file names."),
  915.   N_("--no-ignore-file-name-case  Consider case when comparing file names."),
  916.   N_("-E  --ignore-tab-expansion  Ignore changes due to tab expansion."),
  917.   N_("-b  --ignore-space-change  Ignore changes in the amount of white space."),
  918.   N_("-w  --ignore-all-space  Ignore all white space."),
  919.   N_("-B  --ignore-blank-lines  Ignore changes whose lines are all blank."),
  920.   N_("-I RE  --ignore-matching-lines=RE  Ignore changes whose lines all match RE."),
  921.   N_("--strip-trailing-cr  Strip trailing carriage return on input."),
  922. #if HAVE_SETMODE_DOS
  923.   N_("--binary  Read and write data in binary mode."),
  924. #endif
  925.   N_("-a  --text  Treat all files as text."),
  926.   "",
  927.   N_("-c  -C NUM  --context[=NUM]  Output NUM (default 3) lines of copied context.\n\
  928. -u  -U NUM  --unified[=NUM]  Output NUM (default 3) lines of unified context.\n\
  929.   --label LABEL  Use LABEL instead of file name.\n\
  930.   -p  --show-c-function  Show which C function each change is in.\n\
  931.   -F RE  --show-function-line=RE  Show the most recent line matching RE."),
  932.   N_("-q  --brief  Output only whether files differ."),
  933.   N_("-e  --ed  Output an ed script."),
  934.   N_("--normal  Output a normal diff."),
  935.   N_("-n  --rcs  Output an RCS format diff."),
  936.   N_("-y  --side-by-side  Output in two columns.\n\
  937.   -W NUM  --width=NUM  Output at most NUM (default 130) print columns.\n\
  938.   --left-column  Output only the left column of common lines.\n\
  939.   --suppress-common-lines  Do not output common lines."),
  940.   N_("-D NAME  --ifdef=NAME  Output merged file to show `#ifdef NAME' diffs."),
  941.   N_("--GTYPE-group-format=GFMT  Similar, but format GTYPE input groups with GFMT."),
  942.   N_("--line-format=LFMT  Similar, but format all input lines with LFMT."),
  943.   N_("--LTYPE-line-format=LFMT  Similar, but format LTYPE input lines with LFMT."),
  944.   N_("  LTYPE is `old', `new', or `unchanged'.  GTYPE is LTYPE or `changed'."),
  945.   N_("  GFMT may contain:\n\
  946.     %<  lines from FILE1\n\
  947.     %>  lines from FILE2\n\
  948.     %=  lines common to FILE1 and FILE2\n\
  949.     %[-][WIDTH][.[PREC]]{doxX}LETTER  printf-style spec for LETTER\n\
  950.       LETTERs are as follows for new group, lower case for old group:\n\
  951.         F  first line number\n\
  952.         L  last line number\n\
  953.         N  number of lines = L-F+1\n\
  954.         E  F-1\n\
  955.         M  L+1"),
  956.   N_("  LFMT may contain:\n\
  957.     %L  contents of line\n\
  958.     %l  contents of line, excluding any trailing newline\n\
  959.     %[-][WIDTH][.[PREC]]{doxX}n  printf-style spec for input line number"),
  960.   N_("  Either GFMT or LFMT may contain:\n\
  961.     %%  %\n\
  962.     %c'C'  the single character C\n\
  963.     %c'\\OOO'  the character with octal code OOO"),
  964.   "",
  965.   N_("-l  --paginate  Pass the output through `pr' to paginate it."),
  966.   N_("-t  --expand-tabs  Expand tabs to spaces in output."),
  967.   N_("-T  --initial-tab  Make tabs line up by prepending a tab."),
  968.   "",
  969.   N_("-r  --recursive  Recursively compare any subdirectories found."),
  970.   N_("-N  --new-file  Treat absent files as empty."),
  971.   N_("--unidirectional-new-file  Treat absent first files as empty."),
  972.   N_("-s  --report-identical-files  Report when two files are the same."),
  973.   N_("-x PAT  --exclude=PAT  Exclude files that match PAT."),
  974.   N_("-X FILE  --exclude-from=FILE  Exclude files that match any pattern in FILE."),
  975.   N_("-S FILE  --starting-file=FILE  Start with FILE when comparing directories."),
  976.   N_("--from-file=FILE1  Compare FILE1 to all operands.  FILE1 can be a directory."),
  977.   N_("--to-file=FILE2  Compare all operands to FILE2.  FILE2 can be a directory."),
  978.   "",
  979.   N_("--horizon-lines=NUM  Keep NUM lines of the common prefix and suffix."),
  980.   N_("-d  --minimal  Try hard to find a smaller set of changes."),
  981.   N_("--speed-large-files  Assume large files and many scattered small changes."),
  982.   "",
  983. #ifdef __riscos
  984.   "-&         --append-filetypes      Append filetypes in Acorn NFS format.",
  985.   "-/ [EXT]   --unix-filenames[=EXT]  Output Unix-style filenames with optiona",
  986.   "  EXTension swapping. '-/ c:h:o' causes, eg. 'foo.c.bar' -> 'foo/bar.c'\n",
  987.   "-|FILTER   --filter=FILTER         Filter files. First character in FILTER:",
  988.   "  <  apply (without '<') to first file, or files in first directory",
  989.   "  >  apply (without '>') to second file, or files in second directory",
  990.   "     else apply to all files.\n",
  991.   "",
  992. #endif
  993.   N_("-v  --version  Output version info."),
  994.   N_("--help  Output this help."),
  995.   "",
  996.   N_("FILES are `FILE1 FILE2' or `DIR1 DIR2' or `DIR FILE...' or `FILE... DIR'."),
  997.   N_("If --from-file or --to-file is given, there are no restrictions on FILES."),
  998.   N_("If a FILE is `-', read standard input."),
  999.   "",
  1000.   N_("Report bugs to <bug-gnu-utils@gnu.org>."),
  1001.   0
  1002. };
  1003.  
  1004. static void
  1005. usage (void)
  1006. {
  1007.   char const * const *p;
  1008.  
  1009.   printf (_("Usage: %s [OPTION]... FILES\n"), program_name);
  1010.  
  1011.   for (p = option_help_msgid;  *p;  p++)
  1012.     {
  1013.       if (!**p)
  1014.     putchar ('\n');
  1015.       else
  1016.     {
  1017.       char const *msg = _(*p);
  1018.       char const *nl;
  1019.       while ((nl = strchr (msg, '\n')))
  1020.         {
  1021.           int msglen = nl + 1 - msg;
  1022.           printf ("  %.*s", msglen, msg);
  1023.           msg = nl + 1;
  1024.         }
  1025.  
  1026.       printf ("  %s\n" + 2 * (*msg != ' ' && *msg != '-'), msg);
  1027.     }
  1028.     }
  1029. }
  1030.  
  1031. /* Set VAR to VALUE, reporting an OPTION error if this is a
  1032.    conflict.  */
  1033. static void
  1034. specify_value (char const **var, char const *value, char const *option)
  1035. {
  1036.   if (*var && strcmp (*var, value) != 0)
  1037.     {
  1038.       error (0, 0, _("conflicting %s option value `%s'"), option, value);
  1039.       try_help (0, 0);
  1040.     }
  1041.   *var = value;
  1042. }
  1043.  
  1044. /* Set the output style to STYLE, diagnosing conflicts.  */
  1045. static void
  1046. specify_style (enum output_style style)
  1047. {
  1048.   if (output_style != style)
  1049.     {
  1050.       if (output_style != OUTPUT_UNSPECIFIED)
  1051.     try_help ("conflicting output style options", 0);
  1052.       output_style = style;
  1053.     }
  1054. }
  1055.  
  1056. #ifdef __riscos
  1057. static char const *
  1058. filetype (struct stat const *st)
  1059. {
  1060.   switch (st->st_mode >> 16) {
  1061.     case 1: return st->st_size ? "regular file" : "regular empty file";
  1062.     case 2: return "directory";
  1063.     case 3: return "image file"; /* this is RISC OS specific... */
  1064.   }
  1065.   return "weird file";
  1066. }
  1067. #else
  1068. static char const *
  1069. filetype (struct stat const *st)
  1070. {
  1071.   /* See POSIX 1003.1-2001 for these formats.
  1072.  
  1073.      To keep diagnostics grammatical in English, the returned string
  1074.      must start with a consonant.  */
  1075.  
  1076.   if (S_ISREG (st->st_mode))
  1077.     return st->st_size == 0 ? _("regular empty file") : _("regular file");
  1078.  
  1079.   if (S_ISDIR (st->st_mode)) return _("directory");
  1080.  
  1081. #ifdef S_ISBLK
  1082.   if (S_ISBLK (st->st_mode)) return _("block special file");
  1083. #endif
  1084. #ifdef S_ISCHR
  1085.   if (S_ISCHR (st->st_mode)) return _("character special file");
  1086. #endif
  1087. #ifdef S_ISFIFO
  1088.   if (S_ISFIFO (st->st_mode)) return _("fifo");
  1089. #endif
  1090.   /* S_ISLNK is impossible with `fstat' and `stat'.  */
  1091. #ifdef S_ISSOCK
  1092.   if (S_ISSOCK (st->st_mode)) return _("socket");
  1093. #endif
  1094. #ifdef S_TYPEISMQ
  1095.   if (S_TYPEISMQ (st)) return _("message queue");
  1096. #endif
  1097. #ifdef S_TYPEISSEM
  1098.   if (S_TYPEISSEM (st)) return _("semaphore");
  1099. #endif
  1100. #ifdef S_TYPEISSHM
  1101.   if (S_TYPEISSHM (st)) return _("shared memory object");
  1102. #endif
  1103. #ifdef S_TYPEISTMO
  1104.   if (S_TYPEISTMO (st)) return _("typed memory object");
  1105. #endif
  1106.  
  1107.   return _("weird file");
  1108. }
  1109. #endif
  1110.  
  1111. /* Set the last-modified time of *ST to be the current time.  */
  1112. #ifndef __riscos
  1113. static void
  1114. set_mtime_to_now (struct stat *st)
  1115. {
  1116. #ifdef ST_MTIM_NSEC
  1117.  
  1118. # if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
  1119.   if (clock_gettime (CLOCK_REALTIME, &st->st_mtim) == 0)
  1120.     return;
  1121. # endif
  1122.  
  1123. # if HAVE_GETTIMEOFDAY
  1124.   {
  1125.     struct timeval timeval;
  1126.     if (gettimeofday (&timeval, NULL) == 0)
  1127.       {
  1128.     st->st_mtime = timeval.tv_sec;
  1129.     st->st_mtim.ST_MTIM_NSEC = timeval.tv_usec * 1000;
  1130.     return;
  1131.       }
  1132.   }
  1133. # endif
  1134.  
  1135. #endif /* ST_MTIM_NSEC */
  1136.  
  1137.   time (&st->st_mtime);
  1138. }
  1139. #endif
  1140.  
  1141. /* Compare two files (or dirs) with parent comparison PARENT
  1142.    and names NAME0 and NAME1.
  1143.    (If PARENT is 0, then the first name is just NAME0, etc.)
  1144.    This is self-contained; it opens the files and closes them.
  1145.  
  1146.    Value is EXIT_SUCCESS if files are the same, EXIT_FAILURE if
  1147.    different, EXIT_TROUBLE if there is a problem opening them.  */
  1148.  
  1149. #ifdef __riscos
  1150. /* But first, a function for printing "Only in foo: bar".  */
  1151. static void
  1152. only_in (const char *dir, const char *name)
  1153. {
  1154.   if (extensions_string || append_filetypes)
  1155.     {
  1156.       struct stat st;
  1157.       char *conv, *dot;
  1158.       char *full = dir_file_pathname (dir, name);
  1159.       stat (full, &st);
  1160.       conv = (char *) ro_tounix (full, extensions_string);
  1161.       if (append_filetypes && st.st_type != -1)
  1162.     {
  1163.       dot = xmalloc (strlen (conv) + 5);
  1164.       sprintf (dot, "%s,%03x", conv, st.st_type);
  1165.       conv = dot;
  1166.     }
  1167.       else
  1168.     conv = xstrdup (conv);
  1169.       dot = strrchr (conv, extensions_string ? '/' : '.');
  1170.       if (dot)
  1171.         *dot++ = 0;
  1172.       message ("Only in %s: %s\n", conv, dot ? dot : name);
  1173.       free (full);
  1174.       free (conv);
  1175.     }
  1176.   else
  1177.     message ("Only in %s: %s\n", dir, name);
  1178. }
  1179.  
  1180. static int
  1181. compare_files_nofilter (struct comparison const *parent,
  1182.             char const *name0, char const *name1)
  1183. {
  1184.   return compare_files (parent, name0, name1, 0, 0);
  1185. }
  1186.  
  1187. static int
  1188. compare_files (struct comparison const *parent,
  1189.            char const *name0, char const *name1,
  1190.            char const *filter0, char const *filter1)
  1191. #else
  1192. static int
  1193. compare_files (struct comparison const *parent,
  1194.            char const *name0,
  1195.            char const *name1)
  1196. #endif
  1197. {
  1198.   struct comparison cmp;
  1199. #define DIR_P(f) (S_ISDIR (cmp.file[f].stat.st_mode) != 0)
  1200.   register int f;
  1201.   int status = EXIT_SUCCESS;
  1202.   bool same_files = 0;
  1203.   char *free0, *free1;
  1204.  
  1205.   /* If this is directory comparison, perhaps we have a file
  1206.      that exists only in one of the directories.
  1207.      If so, just print a message to that effect.  */
  1208.  
  1209.   if (! ((name0 && name1)
  1210.      || (unidirectional_new_file && name1)
  1211.      || new_file))
  1212.     {
  1213.       char const *name = name0 == 0 ? name1 : name0;
  1214.       char const *dir = parent->file[name0 == 0].name;
  1215.  
  1216.       /* See POSIX 1003.1-2001 for this format.  */
  1217. #ifdef __riscos
  1218.       only_in (dir, name);
  1219. #else
  1220.       message ("Only in %s: %s\n", dir, name);
  1221. #endif
  1222.  
  1223.       /* Return EXIT_FAILURE so that diff_dirs will return
  1224.      EXIT_FAILURE ("some files differ").  */
  1225.       return EXIT_FAILURE;
  1226.     }
  1227.  
  1228.   memset (cmp.file, 0, sizeof cmp.file);
  1229.   cmp.parent = parent;
  1230.  
  1231.   /* cmp.file[f].desc markers */
  1232. #define NONEXISTENT (-1) /* nonexistent file */
  1233. #define UNOPENED (-2) /* unopened file (e.g. directory) */
  1234. #define ERRNO_ENCODE(errno) (-3 - (errno)) /* encoded errno value */
  1235.  
  1236. #define ERRNO_DECODE(desc) (-3 - (desc)) /* inverse of ERRNO_ENCODE */
  1237.  
  1238.   cmp.file[0].desc = name0 == 0 ? NONEXISTENT : UNOPENED;
  1239.   cmp.file[1].desc = name1 == 0 ? NONEXISTENT : UNOPENED;
  1240.  
  1241.   /* Now record the full name of each file, including nonexistent ones.  */
  1242.  
  1243.   if (name0 == 0)
  1244.     name0 = name1;
  1245.   if (name1 == 0)
  1246.     name1 = name0;
  1247.  
  1248.   if (!parent)
  1249.     {
  1250.       free0 = 0;
  1251.       free1 = 0;
  1252.       cmp.file[0].name = name0;
  1253.       cmp.file[1].name = name1;
  1254. #ifdef __riscos
  1255.       cmp.file[0].filter = filter0;
  1256.       cmp.file[1].filter = filter1;
  1257. #endif
  1258.     }
  1259.   else
  1260.     {
  1261.       cmp.file[0].name = free0
  1262.     = dir_file_pathname (parent->file[0].name, name0);
  1263.       cmp.file[1].name = free1
  1264.     = dir_file_pathname (parent->file[1].name, name1);
  1265.     }
  1266.  
  1267.   /* Stat the files.  */
  1268.  
  1269.   for (f = 0; f < 2; f++)
  1270.     {
  1271. #ifdef __riscos
  1272.       /* Munge the filename.  */
  1273.       int a = append_filetypes && cmp.file[0].stat.st_type != -1;
  1274.       if (extensions_string)
  1275.         cmp.file[f].unixname = ro_tounix (cmp.file[f].name, extensions_string);
  1276.       else
  1277.         cmp.file[f].unixname = cmp.file[f].name;
  1278.       if (a || extensions_string)
  1279.     {
  1280.       char *g = alloca (strlen (cmp.file[f].unixname) + (a ? 5 : 1));
  1281.       if (!g)
  1282.         fatal ("out of memory");
  1283.       if (a)
  1284.         sprintf (g, "%s,%03x", cmp.file[f].unixname, cmp.file[f].stat.st_type);
  1285.       else
  1286.         strcpy (g, cmp.file[f].unixname);
  1287.       cmp.file[f].unixname = g;
  1288.     }
  1289. #endif
  1290.       if (cmp.file[f].desc != NONEXISTENT)
  1291.     {
  1292.       if (f && file_name_cmp (cmp.file[f].name, cmp.file[0].name) == 0)
  1293.         {
  1294.           cmp.file[f].desc = cmp.file[0].desc;
  1295.           cmp.file[f].stat = cmp.file[0].stat;
  1296.         }
  1297.       else if (strcmp (cmp.file[f].name, "-") == 0)
  1298.         {
  1299.           cmp.file[f].desc = STDIN_FILENO;
  1300.           if (fstat (STDIN_FILENO, &cmp.file[f].stat) != 0)
  1301.         cmp.file[f].desc = ERRNO_ENCODE (errno);
  1302.           else
  1303.         {
  1304.           if (S_ISREG (cmp.file[f].stat.st_mode))
  1305.             {
  1306.               off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
  1307.               if (pos < 0)
  1308.             cmp.file[f].desc = ERRNO_ENCODE (errno);
  1309.               else
  1310.             cmp.file[f].stat.st_size =
  1311.               MAX (0, cmp.file[f].stat.st_size - pos);
  1312.             }
  1313.  
  1314.           /* POSIX 1003.1-2001 requires current time for
  1315.              stdin.  */
  1316. #ifdef __riscos
  1317.           time (&cmp.file[f].stat.st_mtime);
  1318.           cmp.file[f].stat.st_type = 0xFFF;
  1319. #else
  1320.           set_mtime_to_now (&cmp.file[f].stat);
  1321. #endif
  1322.         }
  1323.         }
  1324.       else if (stat (cmp.file[f].name, &cmp.file[f].stat) != 0)
  1325.         cmp.file[f].desc = ERRNO_ENCODE (errno);
  1326.     }
  1327.     }
  1328.  
  1329.   /* Mark files as nonexistent at the top level as needed for -N and
  1330.      --unidirectional-new-file.  */
  1331.   if (! parent)
  1332.     {
  1333.       if ((new_file | unidirectional_new_file)
  1334.       && cmp.file[0].desc == ERRNO_ENCODE (ENOENT)
  1335.       && cmp.file[1].desc == UNOPENED)
  1336.     cmp.file[0].desc = NONEXISTENT;
  1337.  
  1338.       if (new_file
  1339.       && cmp.file[0].desc == UNOPENED
  1340.       && cmp.file[1].desc == ERRNO_ENCODE (ENOENT))
  1341.     cmp.file[1].desc = NONEXISTENT;
  1342.     }
  1343.  
  1344.   for (f = 0; f < 2; f++)
  1345.     if (cmp.file[f].desc == NONEXISTENT)
  1346.       cmp.file[f].stat.st_mode = cmp.file[1 - f].stat.st_mode;
  1347.  
  1348.   for (f = 0; f < 2; f++)
  1349.     {
  1350.       int e = ERRNO_DECODE (cmp.file[f].desc);
  1351.       if (0 <= e)
  1352.     {
  1353.       errno = e;
  1354.       perror_with_name (cmp.file[f].name);
  1355.       status = EXIT_TROUBLE;
  1356.     }
  1357.     }
  1358.  
  1359.   if (status == EXIT_SUCCESS && ! parent && DIR_P (0) != DIR_P (1))
  1360.     {
  1361.       /* If one is a directory, and it was specified in the command line,
  1362.      use the file in that dir with the other file's basename.  */
  1363.  
  1364.       int fnm_arg = DIR_P (0);
  1365.       int dir_arg = 1 - fnm_arg;
  1366.       char const *fnm = cmp.file[fnm_arg].name;
  1367.       char const *dir = cmp.file[dir_arg].name;
  1368.       char const *filename = cmp.file[dir_arg].name = free0
  1369.     = dir_file_pathname (dir, base_name (fnm));
  1370.  
  1371.       if (strcmp (fnm, "-") == 0)
  1372.     fatal ("cannot compare `-' to a directory");
  1373.  
  1374.       if (stat (filename, &cmp.file[dir_arg].stat) != 0)
  1375.     {
  1376.       perror_with_name (filename);
  1377.       status = EXIT_TROUBLE;
  1378.     }
  1379.     }
  1380.  
  1381.   if (status != EXIT_SUCCESS)
  1382.     {
  1383.       /* One of the files should exist but does not.  */
  1384.     }
  1385. #ifndef __riscos
  1386.   else if ((same_files
  1387.         = (cmp.file[0].desc != NONEXISTENT
  1388.            && cmp.file[1].desc != NONEXISTENT
  1389.            && 0 < same_file (&cmp.file[0].stat, &cmp.file[1].stat)
  1390.            && same_file_attributes (&cmp.file[0].stat,
  1391.                     &cmp.file[1].stat)))
  1392.        && no_diff_means_no_output)
  1393.     {
  1394.       /* The two named files are actually the same physical file.
  1395.      We know they are identical without actually reading them.  */
  1396.     }
  1397. #endif
  1398.   else if (DIR_P (0) & DIR_P (1))
  1399.     {
  1400.       if (output_style == OUTPUT_IFDEF)
  1401.     fatal ("-D option not supported with directories");
  1402.  
  1403.       /* If both are directories, compare the files in them.  */
  1404.  
  1405.       if (parent && !recursive)
  1406.     {
  1407.       /* But don't compare dir contents one level down
  1408.          unless -r was specified.
  1409.          See POSIX 1003.1-2001 for this format.  */
  1410. #ifdef __riscos
  1411.       message ("Common subdirectories: %s and %s\n",
  1412.            cmp.file[0].unixname, cmp.file[1].unixname);
  1413. #else
  1414.       message ("Common subdirectories: %s and %s\n",
  1415.            cmp.file[0].name, cmp.file[1].name);
  1416. #endif
  1417.     }
  1418.       else
  1419. #ifdef __riscos
  1420.         status = diff_dirs (&cmp, compare_files_nofilter);
  1421. #else
  1422.     status = diff_dirs (&cmp, compare_files);
  1423. #endif
  1424.     }
  1425.   else if ((DIR_P (0) | DIR_P (1))
  1426.        || (parent
  1427.            && (! S_ISREG (cmp.file[0].stat.st_mode)
  1428.            || ! S_ISREG (cmp.file[1].stat.st_mode))))
  1429.     {
  1430.       if (cmp.file[0].desc == NONEXISTENT || cmp.file[1].desc == NONEXISTENT)
  1431.     {
  1432.       /* We have a subdirectory that exists only in one directory.  */
  1433.  
  1434.       if ((DIR_P (0) | DIR_P (1))
  1435.           && recursive
  1436.           && (new_file
  1437.           || (unidirectional_new_file
  1438.               && cmp.file[0].desc == NONEXISTENT)))
  1439. #ifdef __riscos
  1440.         status = diff_dirs (&cmp, compare_files_nofilter);
  1441. #else
  1442.         status = diff_dirs (&cmp, compare_files);
  1443. #endif
  1444.       else
  1445.         {
  1446.           char const *dir
  1447.         = parent->file[cmp.file[0].desc == NONEXISTENT].name;
  1448.  
  1449.           /* See POSIX 1003.1-2001 for this format.  */
  1450. #ifdef __riscos
  1451.           only_in (dir, name0);
  1452. #else
  1453.           message ("Only in %s: %s\n", dir, name0);
  1454. #endif
  1455.  
  1456.           status = EXIT_FAILURE;
  1457.         }
  1458.     }
  1459.       else
  1460.     {
  1461.       /* We have two files that are not to be compared.  */
  1462.  
  1463.       /* See POSIX 1003.1-2001 for this format.  */
  1464. #ifdef __riscos
  1465.       message5 ("File %s is a %s while file %s is a %s\n",
  1466.             file_label[0] ? file_label[0] : cmp.file[0].unixname,
  1467.             filetype (&cmp.file[0].stat),
  1468.             file_label[1] ? file_label[1] : cmp.file[1].unixname,
  1469.             filetype (&cmp.file[1].stat));
  1470. #else
  1471.       message5 ("File %s is a %s while file %s is a %s\n",
  1472.             file_label[0] ? file_label[0] : cmp.file[0].name,
  1473.             filetype (&cmp.file[0].stat),
  1474.             file_label[1] ? file_label[1] : cmp.file[1].name,
  1475.             filetype (&cmp.file[1].stat));
  1476. #endif
  1477.  
  1478.       /* This is a difference.  */
  1479.       status = EXIT_FAILURE;
  1480.     }
  1481.     }
  1482.   else if (files_can_be_treated_as_binary
  1483.        && cmp.file[0].stat.st_size != cmp.file[1].stat.st_size
  1484.        && (cmp.file[0].desc == NONEXISTENT
  1485.            || S_ISREG (cmp.file[0].stat.st_mode))
  1486.        && (cmp.file[1].desc == NONEXISTENT
  1487.            || S_ISREG (cmp.file[1].stat.st_mode)))
  1488.     {
  1489. #ifdef __riscos
  1490.       message ("Files %s and %s differ\n",
  1491.            file_label[0] ? file_label[0] : cmp.file[0].unixname,
  1492.            file_label[1] ? file_label[1] : cmp.file[1].unixname);
  1493. #else
  1494.       message ("Files %s and %s differ\n",
  1495.            file_label[0] ? file_label[0] : cmp.file[0].name,
  1496.            file_label[1] ? file_label[1] : cmp.file[1].name);
  1497. #endif
  1498.       status = EXIT_FAILURE;
  1499.     }
  1500.   else
  1501.     {
  1502.       /* Both exist and neither is a directory.  */
  1503.  
  1504.       /* Open the files and record their descriptors.  */
  1505.  
  1506.       if (cmp.file[0].desc == UNOPENED)
  1507.     if ((cmp.file[0].desc = open (cmp.file[0].name, O_RDONLY, 0)) < 0)
  1508.       {
  1509.         perror_with_name (cmp.file[0].name);
  1510.         status = EXIT_TROUBLE;
  1511.       }
  1512.       if (cmp.file[1].desc == UNOPENED)
  1513.     {
  1514.       if (same_files)
  1515.         cmp.file[1].desc = cmp.file[0].desc;
  1516.       else if ((cmp.file[1].desc = open (cmp.file[1].name, O_RDONLY, 0))
  1517.            < 0)
  1518.         {
  1519.           perror_with_name (cmp.file[1].name);
  1520.           status = EXIT_TROUBLE;
  1521.         }
  1522.     }
  1523.  
  1524. #if HAVE_SETMODE_DOS
  1525.       if (binary)
  1526.     for (f = 0; f < 2; f++)
  1527.       if (0 <= cmp.file[f].desc)
  1528.         set_binary_mode (cmp.file[f].desc, 1);
  1529. #endif
  1530.  
  1531.       /* Compare the files, if no error was found.  */
  1532.  
  1533.       if (status == EXIT_SUCCESS)
  1534.     status = diff_2_files (&cmp);
  1535.  
  1536.       /* Close the file descriptors.  */
  1537.  
  1538.       if (0 <= cmp.file[0].desc && close (cmp.file[0].desc) != 0)
  1539.     {
  1540.       perror_with_name (cmp.file[0].name);
  1541.       status = EXIT_TROUBLE;
  1542.     }
  1543.       if (0 <= cmp.file[1].desc && cmp.file[0].desc != cmp.file[1].desc
  1544.       && close (cmp.file[1].desc) != 0)
  1545.     {
  1546.       perror_with_name (cmp.file[1].name);
  1547.       status = EXIT_TROUBLE;
  1548.     }
  1549.     }
  1550.  
  1551.   /* Now the comparison has been done, if no error prevented it,
  1552.      and STATUS is the value this function will return.  */
  1553.  
  1554.   if (status == EXIT_SUCCESS)
  1555.     {
  1556.       if (report_identical_files && !DIR_P (0))
  1557. #ifdef __riscos
  1558.     message ("Files %s and %s are identical\n",
  1559.          file_label[0] ? file_label[0] : cmp.file[0].unixname,
  1560.          file_label[1] ? file_label[1] : cmp.file[1].unixname);
  1561. #else
  1562.     message ("Files %s and %s are identical\n",
  1563.          file_label[0] ? file_label[0] : cmp.file[0].name,
  1564.          file_label[1] ? file_label[1] : cmp.file[1].name);
  1565. #endif
  1566.     }
  1567.   else
  1568.     {
  1569.       /* Flush stdout so that the user sees differences immediately.
  1570.      This can hurt performance, unfortunately.  */
  1571.       if (fflush (stdout) != 0)
  1572.     pfatal_with_name (_("standard output"));
  1573.     }
  1574.  
  1575.   if (free0)
  1576.     free (free0);
  1577.   if (free1)
  1578.     free (free1);
  1579.  
  1580.   return status;
  1581. }
  1582.